<template>
  <div class="map-home">
    <div id="MapContainer"></div>
    <div class="info-box">
      <el-input
        v-model.lazy="keyword"
        id="searchMap"
        ref="searchMap"
        placeholder="输入关键字搜索"
        style="width: 300px"
        @input="handleSearch"
      >
      </el-input>
      <div class="ulInfo" v-if="data.length > 0">
        <div
          class="li"
          v-for="item in data"
          :key="item.id"
          @click="handleSelect(item)"
        >
          <div class="d-flex flex-column">
            <span
              style="margin-bottom: 6px; font-weight: 700; color: #009688"
              >{{ item.name }}</span
            >
            <span style="margin-bottom: 6px; font-size: 12px"
              >地址：{{ item.address }}</span
            >
            <span style="margin-bottom: 6px; font-size: 12px"
              >坐标：{{ item.location }}</span
            >
            <!-- <span>{{ item }}</span> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { shallowRef, defineEmits, ref, defineProps, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
const securityJsCode = "278c5e056386979f0fd084461f5f6b6f";
const map_key = "9203a24c5b563165740aba9d54dae047";
declare global {
  interface Window {
    _AMapSecurityConfig?: {
      securityJsCode: string;
    };
  }
}
window._AMapSecurityConfig = {
  securityJsCode: securityJsCode,
};
const map = shallowRef<any>(null); //
const keyword = ref("");
const addresstext = ref("");
const data = ref<any[]>([]);
const coord = ref("");
const adcode = ref("");

const searchMap = ref("");
let AMapObj: any = null;
let placeSearch: string | null = null;
let marker: any = null;
let geocoder: {
  getAddress: (
    arg0: any[],
    arg1: { (status: any, result: any): void; (status: any, result: any): void }
  ) => void;
} | null = null;
let AutoComplete = null;

const props = defineProps({
  form: {},
  parentCustom: String,
});

watch(
  () => props.parentCustom,
  (newVal, oldVal) => {
    if (newVal) {
      keyword.value = newVal;
      handleSearch(newVal);
    }
  }
);

async function initMap() {
  AMapLoader.load({
    key: map_key, //设置您的key
    version: "2.0",
    plugins: [
      "AMap.ToolBar",
      "AMap.ElasticMarker",
      "AMap.AutoComplete",
      "AMap.PlaceSearch",
      "AMap.moveAnimation",
    ],
  })
    .then((AMap) => {
      // console.log(AMap);
      AMapObj = AMap;
      map.value = new AMap.Map("MapContainer", {
        viewMode: "2D", //默认使用 2D 模式
        zoom: 14, //地图级别
      });
      if (map.value) {
        map.value.on("click", onMapClick);
      }
      AMap.plugin(
        [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.Geolocation",
          "AMap.PlaceSearch",
          "AMap.Geocoder",
          "AMap.AutoComplete",
        ],
        () => {
          // 缩放条
          const toolbar = new AMap.ToolBar();
          // 比例尺
          const scale = new AMap.Scale();
          // 定位
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认:true
            timeout: 10000, // 超过10秒后停止定位，默认：5s
            position: "RT", // 定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
            extensions: "all",
          });
          geocoder = new AMap.Geocoder({
            city: "全国",
          });
          map.value.addControl(geolocation);
          map.value.addControl(toolbar);
          map.value.addControl(scale);
          placeSearch = new AMap.PlaceSearch({
            city: "全国",
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            citylimit: false, // 是否强制限制在设置的城市内搜索
            extensions: "all",
            autoFitView: true,
          });
        }
      );
    })
    .catch((e) => {
      console.log(e);
    });
}

// 搜索地图
async function handleSearch(str: string) {
  keyword.value = str;
  placeSearch?.search(str, (status, result) => {
    if (result && typeof result === "object" && result.poiList) {
      const list = result.poiList.pois;
      list.forEach((item) => {
        item.value = item.name;
        item.label = item.name;
      });
      data.value = list;
    }
  });
}

// 点击地图
async function onMapClick(e: any) {
  coord.value = e.lnglat.lng + "," + e.lnglat.lat;
  geocoder?.getAddress([e.lnglat.lng, e.lnglat.lat], function (status, result) {
    if (status === "complete" && result.info === "OK") {
      // result为对应的地理位置详细信息
      keyword.value = result.regeocode.formattedAddress;
      addresstext.value = result.regeocode.formattedAddress;
      adcode.value =
        result.regeocode.addressComponent.adcode.slice(0, 4) + "00";
      let pname = result.regeocode.addressComponent.province;
      let cityname = result.regeocode.addressComponent.city;
      let adname = result.regeocode.addressComponent.district;
      let mapInfo = {
        location: {
          lng: e.lnglat.lng,
          lat: e.lnglat.lat,
        },
        name: addresstext.value,
        address: addresstext.value,
        pname: pname,
        cityname: cityname,
        adname: adname,
      };
      drawMarker(mapInfo);
      handleSearch(keyword.value);
    }
  });
}
async function onMapadcode(e: any) {
  geocoder?.getAddress(
    [e.location.lng, e.location.lat],
    function (status, result) {
      if (status === "complete" && result.info === "OK") {
        // result为对应的地理位置详细信息
        adcode.value =
          result.regeocode.addressComponent.adcode.slice(0, 4) + "00";
      }
    }
  );
}

// 点击地址向父组件传递数据
const emit = defineEmits(["setAddress"]);
// 点击搜索项
async function handleSelect(item: any) {
  drawMarker(item);
  onMapadcode(item);
  let addressInfo = "";
  if (item.location != null) {
    coord.value = item.location.lng + "," + item.location.lat;
    keyword.value = item.name;
    addresstext.value = item.address;
    emit("setAddress", {
      lng: item.location.lng,
      lat: item.location.lat,
      address: addresstext.value,
      province_name: item.pname,
      city_name: item.cityname,
      county_name: item.adname,
      customer_name: item.name,
    });
  }
}

async function openInfo(longitude: string, latitude: string, item: any) {
  //构建信息窗体中显示的内容
  var info = [];

  info.push('<div class="input-title"><h7>' + item.name + "</h7>");
  // info.push("<div class='input-item'>地址 : " + item.address + "</div>");
  // info.push(
  //   "<div class='input-item'>坐标 :" +
  //     longitude +
  //     "," +
  //     latitude +
  //     "</div></div>"
  // );

  const infoWindow = new AMapObj.InfoWindow({
    content: info.join(""), //使用默认信息窗体框样式，显示信息内容
  });

  infoWindow.open(map.value, [longitude, latitude]);
  map.value.setCenter([longitude, latitude]);
}
// 绘制地点marker
async function drawMarker(item: any) {
  if (location == null) return;
  let longitude = item.location.lng,
    latitude = item.location.lat;
  if (marker) {
    marker.setMap(null);
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: "bottom-center",
    title: item.name,
  });
  marker.on("click", () => {
    coord.value = item.location;
  });
  map.value.add(marker);
  //infoWindow.open(map.value, [longitude, latitude]);
  map.value.setZoomAndCenter(14, [longitude, latitude]);
  openInfo(longitude, latitude, item);
}

initMap();
defineExpose({
  handleSelect,
  drawMarker,
  data,
  initMap,
  handleSearch,
  keyword,
});
</script>

<style lang="scss" scoped>
.map-home {
  position: relative;
  width: 100%;
  height: 800px;
  padding: 0;
  margin: 0;
  .amap-container {
    width: 100%;
    height: calc(100% - 30px);
  }
  .info-box {
    position: absolute;
    top: 8px;
    right: 8px;
    display: flex;
    flex-direction: column;
    width: 300px;
    height: 100%;
  }
}
.ulInfo {
  height: 60%;
  margin-top: 10px;
  overflow-y: scroll;
  background: #ffffff;
  .li {
    min-height: 60px;
    padding: 5px 10px;
    margin-bottom: 10px;
    background: #ffffff;
    border-bottom: 1px solid #f2f2f2;
    .d-flex {
      display: flex;
      flex-direction: column;
      color: #1f1f1f;
      background: #ffffff;
    }
  }
}
#map-box {
  width: 100%;
  height: calc(100% - 30px);
  padding: 0;
  margin: 0;
}
.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}
</style>

<style scoped>
:deep() .amap-logo {
  display: none !important;
}
:deep() .amap-copyright {
  display: none !important;
}
::v-deep(.input-item) {
  height: 20px;
  font-size: 14px;
  line-height: 28px;
  color: #666666;
}
</style>
